
const CryptoJS = require('crypto-js')

function GetRandomNum(n) {
  const chars = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
    'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
    'W', 'X', 'Y', 'Z', '.', '?', '~', '!', '@', '#', '$', '%', '^', '&', '*']
  if (n == null) {
    n = 16
  }
  let res = ''
  for (let i = 0; i < n; i++) {
    const id = Math.ceil(Math.random() * 46)
    res += chars[id]
  }
  return res
}

function GetUuid() {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    const indexStart = Math.floor(Math.random() * 0x10)
    s[i] = hexDigits.substring(indexStart, indexStart + 1)
  }
  s[14] = '4'
  const indexStart = (s[19] & 0x3) | 0x8
  s[19] = hexDigits.substring(indexStart, indexStart + 1)
  s[8] = s[13] = s[18] = s[23] = '-'
  return s.join('')
}

function Decrypt(word, k, iv) {
  const key = CryptoJS.enc.Utf8.parse(k)
  const base64 = CryptoJS.enc.Base64.parse(word)
  const src = CryptoJS.enc.Base64.stringify(base64)
  var decrypt = CryptoJS.AES.decrypt(src, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding })
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}

function Encrypt(word, k, iv) {
  const key = CryptoJS.enc.Utf8.parse(k)
  const src = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(src, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding })
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

export default {
  Decrypt,
  Encrypt,
  GetRandomNum,
  GetUuid
}
